<template>
  <el-dialog
    v-model="visible"
    title="创建试卷"
    width="900px"
    @close="handleClose"
  >
    <el-form
      ref="formRef"
      :model="form"
      :rules="rules"
      label-width="120px"
    >
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="试卷标题" prop="title">
            <el-input
              v-model="form.title"
              placeholder="请输入试卷标题"
              maxlength="100"
              show-word-limit
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="考试科目" prop="subject">
            <el-select
              v-model="form.subject"
              placeholder="请选择科目"
              style="width: 100%"
            >
              <el-option label="语文" value="chinese" />
              <el-option label="数学" value="math" />
              <el-option label="英语" value="english" />
              <el-option label="物理" value="physics" />
              <el-option label="化学" value="chemistry" />
              <el-option label="生物" value="biology" />
              <el-option label="历史" value="history" />
              <el-option label="地理" value="geography" />
              <el-option label="政治" value="politics" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="适用年级" prop="grade">
            <el-select
              v-model="form.grade"
              placeholder="请选择年级"
              style="width: 100%"
            >
              <el-option label="一年级" value="1" />
              <el-option label="二年级" value="2" />
              <el-option label="三年级" value="3" />
              <el-option label="四年级" value="4" />
              <el-option label="五年级" value="5" />
              <el-option label="六年级" value="6" />
              <el-option label="七年级" value="7" />
              <el-option label="八年级" value="8" />
              <el-option label="九年级" value="9" />
              <el-option label="高一" value="10" />
              <el-option label="高二" value="11" />
              <el-option label="高三" value="12" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="试卷类型" prop="paper_type">
            <el-select
              v-model="form.paper_type"
              placeholder="请选择试卷类型"
              style="width: 100%"
            >
              <el-option label="期中考试" value="midterm" />
              <el-option label="期末考试" value="final" />
              <el-option label="单元测试" value="unit" />
              <el-option label="模拟考试" value="mock" />
              <el-option label="练习卷" value="practice" />
              <el-option label="竞赛卷" value="competition" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="8">
          <el-form-item label="总分" prop="total_score">
            <el-input-number
              v-model="form.total_score"
              :min="10"
              :max="200"
              :step="10"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="及格分数" prop="passing_score">
            <el-input-number
              v-model="form.passing_score"
              :min="1"
              :max="form.total_score - 1"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="考试时长" prop="duration">
            <el-input-number
              v-model="form.duration"
              :min="30"
              :max="300"
              :step="15"
              style="width: 100%"
            />
            <span style="margin-left: 8px; color: #909399;">分钟</span>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="难度等级" prop="difficulty_level">
            <el-select
              v-model="form.difficulty_level"
              placeholder="请选择难度等级"
              style="width: 100%"
            >
              <el-option label="简单" value="easy" />
              <el-option label="中等" value="medium" />
              <el-option label="困难" value="hard" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="创建方式" prop="create_mode">
            <el-radio-group v-model="form.create_mode">
              <el-radio value="manual">手动组卷</el-radio>
              <el-radio value="template">使用模板</el-radio>
              <el-radio value="auto">智能组卷</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
      </el-row>

      <el-form-item label="试卷描述" prop="description">
        <el-input
          v-model="form.description"
          type="textarea"
          :rows="3"
          placeholder="请输入试卷描述"
          maxlength="500"
          show-word-limit
        />
      </el-form-item>

      <!-- 模板选择 -->
      <el-form-item v-if="form.create_mode === 'template'" label="选择模板" prop="template_id">
        <el-select
          v-model="form.template_id"
          placeholder="请选择试卷模板"
          style="width: 100%"
          filterable
        >
          <el-option
            v-for="template in templates"
            :key="template.id"
            :label="`${template.title} (${template.subject} - ${template.grade}年级)`"
            :value="template.id"
          />
        </el-select>
      </el-form-item>

      <!-- 智能组卷参数 -->
      <template v-if="form.create_mode === 'auto'">
        <el-divider content-position="left">智能组卷参数</el-divider>

        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="知识点覆盖" prop="coverage">
              <el-slider
                v-model="form.auto_params.coverage"
                :min="50"
                :max="100"
                show-input
                :show-input-controls="false"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="难度分布" prop="difficulty_distribution">
              <el-select v-model="form.auto_params.difficulty_distribution" style="width: 100%">
                <el-option label="简单为主" value="easy_focused" />
                <el-option label="均衡分布" value="balanced" />
                <el-option label="困难为主" value="hard_focused" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="题型多样性" prop="question_diversity">
              <el-switch v-model="form.auto_params.question_diversity" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="重点知识点" prop="key_points">
          <el-select
            v-model="form.auto_params.key_points"
            multiple
            filterable
            allow-create
            placeholder="请输入或选择重点知识点"
            style="width: 100%"
          >
            <el-option label="函数与方程" value="functions" />
            <el-option label="几何证明" value="geometry" />
            <el-option label="概率统计" value="probability" />
            <el-option label="力学分析" value="mechanics" />
            <el-option label="化学方程式" value="chemical_equations" />
          </el-select>
        </el-form-item>
      </template>
    </el-form>

    <template #footer>
      <el-button @click="handleClose">取消</el-button>
      <el-button type="primary" @click="handleConfirm" :loading="loading">
        确认创建
      </el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage } from 'element-plus'

interface Props {
  modelValue: boolean
}

interface Emits {
  (e: 'update:modelValue', value: boolean): void
  (e: 'success', data: any): void
}

const props = defineProps<Props>()
const emit = defineEmits<Emits>()

const formRef = ref()
const loading = ref(false)
const templates = ref([])

const visible = computed({
  get: () => props.modelValue,
  set: (value) => emit('update:modelValue', value)
})

const form = reactive({
  title: '',
  subject: '',
  grade: '',
  paper_type: 'midterm',
  total_score: 100,
  passing_score: 60,
  duration: 120,
  difficulty_level: 'medium',
  description: '',
  create_mode: 'manual',
  template_id: null,
  auto_params: {
    coverage: 80,
    difficulty_distribution: 'balanced',
    question_diversity: true,
    key_points: []
  }
})

const rules = {
  title: [
    { required: true, message: '请输入试卷标题', trigger: 'blur' },
    { min: 2, max: 100, message: '长度在 2 到 100 个字符', trigger: 'blur' }
  ],
  subject: [
    { required: true, message: '请选择考试科目', trigger: 'change' }
  ],
  grade: [
    { required: true, message: '请选择适用年级', trigger: 'change' }
  ],
  paper_type: [
    { required: true, message: '请选择试卷类型', trigger: 'change' }
  ],
  total_score: [
    { required: true, message: '请输入总分', trigger: 'blur' },
    { type: 'number', min: 10, max: 200, message: '总分在 10-200 之间', trigger: 'blur' }
  ],
  passing_score: [
    { required: true, message: '请输入及格分数', trigger: 'blur' },
    { type: 'number', min: 1, message: '及格分数必须大于0', trigger: 'blur' }
  ],
  duration: [
    { required: true, message: '请输入考试时长', trigger: 'blur' },
    { type: 'number', min: 30, max: 300, message: '时长在 30-300 分钟之间', trigger: 'blur' }
  ],
  difficulty_level: [
    { required: true, message: '请选择难度等级', trigger: 'change' }
  ],
  create_mode: [
    { required: true, message: '请选择创建方式', trigger: 'change' }
  ],
  template_id: [
    {
      required: true,
      message: '请选择试卷模板',
      trigger: 'change',
      validator: (rule: any, value: any, callback: any) => {
        if (form.create_mode === 'template' && !value) {
          callback(new Error('请选择试卷模板'))
        } else {
          callback()
        }
      }
    }
  ]
}

const fetchTemplates = async () => {
  try {
    // TODO: 调用API获取模板列表
    // const response = await examPaperApi.getTemplates()
    // templates.value = response.data.results

    // 模拟数据
    templates.value = [
      { id: 1, title: '七年级数学期中模板', subject: 'math', grade: '7' },
      { id: 2, title: '八年级物理期末模板', subject: 'physics', grade: '8' },
      { id: 3, title: '高一化学月考模板', subject: 'chemistry', grade: '10' }
    ]
  } catch (error) {
    console.error('获取模板列表失败:', error)
  }
}

const handleClose = () => {
  visible.value = false
  resetForm()
}

const resetForm = () => {
  Object.assign(form, {
    title: '',
    subject: '',
    grade: '',
    paper_type: 'midterm',
    total_score: 100,
    passing_score: 60,
    duration: 120,
    difficulty_level: 'medium',
    description: '',
    create_mode: 'manual',
    template_id: null,
    auto_params: {
      coverage: 80,
      difficulty_distribution: 'balanced',
      question_diversity: true,
      key_points: []
    }
  })
  formRef.value?.clearValidate()
}

const handleConfirm = async () => {
  try {
    await formRef.value.validate()

    loading.value = true

    // TODO: 根据创建方式调用不同的API
    let apiCall
    switch (form.create_mode) {
      case 'template':
        // apiCall = examPaperApi.createPaperFromTemplate
        break
      case 'auto':
        // apiCall = examPaperApi.autoGeneratePaper
        break
      default:
        // apiCall = examPaperApi.createPaper
        break
    }

    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 1500))

    ElMessage.success('试卷创建成功')
    emit('success', { ...form })
    handleClose()
  } catch (error) {
    console.error('创建试卷失败:', error)
    ElMessage.error('创建试卷失败')
  } finally {
    loading.value = false
  }
}

onMounted(() => {
  fetchTemplates()
})
</script>

<style scoped lang="scss">
:deep(.el-divider__text) {
  background-color: #f5f5f5;
}

:deep(.el-slider__runway) {
  margin: 16px 0;
}
</style>